import axios from 'axios'
import { ElMessage } from 'element-plus'
import docCookies from './cookieutil'
//import fetchutil from "./fetchutil";

const request = axios.create({
	baseURL: '/api',  
    timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    if(localStorage.getItem('access_token')!=null)config.headers['Authorization']='Bearer '+localStorage.getItem('access_token')
 // config.headers['token'] = user.token;  // 设置请求头
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        if(res.success==false){
            ElMessage({
                message: res.msg,
                type: "error",
            })
        }
        if(res.code==24161){
            localStorage.clear()
            console.log('移除token',docCookies.removeItem('cic-token'));
            
            // console.log(response);
            // ElMessage({
            //     message: 'token已过期，正在使用获取新token',
            //     type: "warning",
            // })
            // fetchutil.post('/refresh_token',{refresh_token:localStorage.getItem('refresh_token')},(data)=>{
            //     localStorage.setItem("access_token", data.data.access_token);
            //     localStorage.setItem("refresh_token", data.data.refresh_token);
            //     document.cookie = 'token='+data.data.access_token+'; max-age=" + 30*24*60*60'
            //     ElMessage({
            //         message: data.msg,
            //         type: data.code==200?"success":'error',
            //     })
            // })
            // request.post('/refresh_token',JSON.stringify({refresh_token:localStorage.getItem('refresh_token')})).then(data=>{
            //     console.log(data);
            // })
        }
        return res;
    },
    error => {
        if(error.response!=undefined&&error.response.status!=403)
            ElMessage({message: error,type: "error",})
        return Promise.reject(error)
    }
)


export default request